//
//  weixin.m
//  share
//
//  Created by sxiaojian on 14-8-6.
//  Copyright (c) 2014年 com.haomee. All rights reserved.
//

#import "Weixin.h"
#import "WXApi.h"
#import "shareConfig.h"
@interface Weixin()
@property (nonatomic,strong) void (^successBlock)(PlatformUserMoidel *model);
@property (nonatomic,strong) void (^failedBlock)(NSString *message);

@property (nonatomic,strong) void (^shareSuccess)(bool isSuccess);

@end
@implementation Weixin
+ (Weixin *)sharedInstance{
    static Weixin *_sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[Weixin alloc] init];
        [_sharedInstance setup];
    });
    
    return _sharedInstance;
}
- (void)setup
{
    [WXApi registerApp:WXAppID];
}
-(void)getUSerInfoSuccess:(void (^)(PlatformUserMoidel *))success error:(void (^)(NSString *))errorBlock
{
    self.successBlock = [success copy];
    self.failedBlock = [errorBlock copy];
    SendAuthReq *request = [[SendAuthReq alloc] init];
    request.scope = @"snsapi_message,snsapi_userinfo,snsapi_friend,snsapi_contact"; // @"post_timeline,sns"
    request.state = @"xxx";
    [WXApi sendReq:request];
  
}
-(void)shareImage:(UIImage *)image title:(NSString *)title description:(NSString *)description andImageUrl:(NSString *)ImgUrl andurl:(NSString *)url andCompletionBlock:(void (^)(BOOL))block
{
    if ([WXApi isWXAppInstalled]) {
        self.shareSuccess = [block copy];
        WXMediaMessage *message = [WXMediaMessage message];
        message.title = title;
        message.description = description;
        if (image) {
          UIImage *thumbImage = [self resize:CGSizeMake(100, 100) image:image];
            NSData *date = UIImageJPEGRepresentation(thumbImage, 1);
            float a = date.length;
            if (a<32000) {
                [message setThumbImage:thumbImage];
            }
        }else if (ImgUrl) {
            NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImgUrl]];
            UIImage *image = [UIImage imageWithData:imgData];
            UIImage *thumbImage = [self resize:CGSizeMake(100, 100) image:image];
            NSData *date = UIImageJPEGRepresentation(thumbImage, 1);
            float a = date.length;
            if (a<32000) {
                [message setThumbImage:thumbImage];
            }

        }
        
        
        
        if (url) {
        WXWebpageObject *ext = [WXWebpageObject object];
        ext.webpageUrl = url;
        message.mediaObject = ext;
        }
        SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
        req.bText = NO;
        req.message = message;
        if (self.isFriend) {
            req.scene = WXSceneTimeline;
        } else {
            req.scene = WXSceneSession;
        }
        
        
        [WXApi sendReq:req];
    }else{
        NSLog(@"没有安装微信");
    }

    
}
-(BOOL)openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    return [WXApi handleOpenURL:url delegate:self];
}
-(void) onReq:(BaseReq*)req
{
    
}
-(void) onResp:(BaseResp*)resp
{
    if([resp isKindOfClass:[SendMessageToWXResp class]])
    {
        void (^shareSuccess)(BOOL isSuccess) = [self.shareSuccess copy];
        if(resp.errCode == 0) {
            
            shareSuccess(YES);
        }else
        {
            shareSuccess(NO);
        }

    }
    else if([resp isKindOfClass:[SendAuthResp class]])
    {
        SendAuthResp *temp = (SendAuthResp*)resp;
        
        NSString *strTitle = [NSString stringWithFormat:@"Auth结果"];
        NSString *strMsg = [NSString stringWithFormat:@"code:%@,state:%@,errcode:%d", temp.code, temp.state, temp.errCode];
     if(temp.errCode == 0)
     {
         NSLog(@"用户同意");
     }else if (temp.errCode == -2)
     {
       NSLog(@"用户拒绝授权");
     }else if (temp.errCode == -4)
     {
     NSLog(@"用户取消");
     }
     //通过同步请求来获取tocken
        NSString *url = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",WXAppID,WXsecret,temp.code];
        NSURLRequest *request = [[NSURLRequest alloc]initWithURL:[NSURL URLWithString:url]];
        NSData *returnData = [NSURLConnection sendSynchronousRequest:request
                                                   returningResponse:nil error:nil];
        NSError *error;
        NSDictionary *info = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:&error];
        if (error) {
            
        }
        [[NSUserDefaults standardUserDefaults] setObject:info forKey:WXAppID];
        [[NSUserDefaults standardUserDefaults] synchronize];
        //通过同步请求获取用户信息
        NSString *url2 = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",info[@"access_token"],info[@"openid"]];
        NSURLRequest *request2 = [[NSURLRequest alloc]initWithURL:[NSURL URLWithString:url2]];
        NSData *returnData2 = [NSURLConnection sendSynchronousRequest:request2
                                                   returningResponse:nil error:nil];
        NSError *error2;
        NSDictionary *info2 = [NSJSONSerialization JSONObjectWithData:returnData2 options:NSJSONReadingMutableContainers error:&error2];
        PlatformUserMoidel *model = [PlatformUserMoidel new];

        model.userId = info2[@"openid"];
        model.nickname = info2[@"nickname"];
        model.avatar = info2[@"headimgurl"];
        model.orginalData = info2;
        if ([info2[@"sex"] integerValue] == 1) {
            model.gender = @"男";
        }
        else{
            model.gender = @"女";
        }
        model.platform = @"weixin";
        
        void (^successBlock)(PlatformUserMoidel *model) = [self.successBlock copy];
        if (successBlock) {
            successBlock(model);
        }
        
    }
}
- (UIImage*)resize:(CGSize)size image:(UIImage *)image
{
    int W = size.width;
    int H = size.height;
    
    CGImageRef   imageRef   = image.CGImage;
    CGColorSpaceRef colorSpaceInfo = CGImageGetColorSpace(imageRef);
    
    
    CGContextRef bitmap = CGBitmapContextCreate(NULL, W, H, 8, 4*W, colorSpaceInfo, kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little);
    
    if(image.imageOrientation == UIImageOrientationLeft || image.imageOrientation == UIImageOrientationRight){
        W = size.height;
        H = size.width;
    }
    
    if(image.imageOrientation == UIImageOrientationLeft || image.imageOrientation == UIImageOrientationLeftMirrored){
        CGContextRotateCTM (bitmap, M_PI/2);
        CGContextTranslateCTM (bitmap, 0, -H);
    }
    else if (image.imageOrientation == UIImageOrientationRight || image.imageOrientation == UIImageOrientationRightMirrored){
        CGContextRotateCTM (bitmap, -M_PI/2);
        CGContextTranslateCTM (bitmap, -W, 0);
    }
    else if (image.imageOrientation == UIImageOrientationUp || image.imageOrientation == UIImageOrientationUpMirrored){
        // Nothing
    }
    else if (image.imageOrientation == UIImageOrientationDown || image.imageOrientation == UIImageOrientationDownMirrored){
        CGContextTranslateCTM (bitmap, W, H);
        CGContextRotateCTM (bitmap, -M_PI);
    }
    
    CGContextDrawImage(bitmap, CGRectMake(0, 0, W, H), imageRef);
    CGImageRef ref = CGBitmapContextCreateImage(bitmap);
    UIImage* newImage = [UIImage imageWithCGImage:ref];
    
    CGContextRelease(bitmap);
    CGImageRelease(ref);
    return newImage;
}

@end
